/* Copyright 2012-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.snakerflow.framework.ws.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.HistoryTask;
import org.snaker.engine.entity.Process;
import org.snaker.engine.entity.Task;
import org.snaker.engine.helper.AssertHelper;
import org.snaker.engine.model.ProcessModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.snakerflow.framework.flow.SnakerHelper;
import com.snakerflow.framework.flow.dao.ApprovalDao;
import com.snakerflow.framework.flow.service.SnakerEngineFacets;


/**
 * Snaker流程引擎流程相关Controller
 * @author 何东
 * @since 0.1
 */
@Controller
@RequestMapping(value = "/ws/snaker/process")
public class WsProcessController {
	private static Log log = LogFactory.getLog(WsProcessController.class);
	
	/** 操作员 状态（正常） */
	private static final String OPERATOR_STATUS = "running";
	
	@Autowired
	ApprovalDao approvalDao;
	
	@Autowired
	private SnakerEngineFacets facets;
	
	/**
	 * 查询流程图
	 * @param processId
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "flowDiagram", method=RequestMethod.GET)
	@ResponseBody
	public Object flowDiagram(String processId, String orderId) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		if ((StringUtils.isBlank(processId) || null == processId || "null".equals(processId)) 
				&& (StringUtils.isBlank(orderId) || null == orderId || "null".equals(orderId)))
			return jsonMap;
		
		HistoryOrder ho = null;
		if ((StringUtils.isBlank(processId) || null == processId || "null".equals(processId)) 
				&& StringUtils.isNotBlank(orderId) && !"null".equals(orderId)) {
			ho = facets.getEngine().query().getHistOrder(orderId);
			
			if (ho == null)
				return jsonMap;
			
			processId = ho.getProcessId();
		}
		
		Process process = facets.getEngine().process().getProcessById(processId);
        AssertHelper.notNull(process);
        ProcessModel model = process.getModel();
        if(model != null) {
            jsonMap.put("process", SnakerHelper.getModelJson(model));
        }

		if(StringUtils.isNotEmpty(orderId)) {
			List<Task> tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId));
			List<HistoryTask> historyTasks = facets.getEngine().query().getHistoryTasks(new QueryFilter().setOrderId(orderId));
			jsonMap.put("state", SnakerHelper.getStateJson(model, tasks, historyTasks));
		}
		log.info(jsonMap.get("state"));
        //{"historyRects":{"rects":[{"paths":["TO 任务1"],"name":"开始"},{"paths":["TO 分支"],"name":"任务1"},{"paths":["TO 任务3","TO 任务4","TO 任务2"],"name":"分支"}]}}
		return jsonMap;
	}
	
	/**
	 * 查询流程图中任务节点提示信息
	 * @param orderId
	 * @param taskName
	 * @return
	 */
	@RequestMapping(value = "nodeTip", method=RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getProcessNodeTip(String orderId, String taskName) {
        List<Task> tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId));
        StringBuilder builder = new StringBuilder();
        String createTime = "";
        for(Task task : tasks) {
            if(task.getTaskName().equalsIgnoreCase(taskName)) {
                String[] actors = facets.getEngine().query().getTaskActorsByTaskId(task.getId());
                for(String actor : actors) {
                	String userIds = getOperatorNamesByRoleName(actor);
                    builder.append(StringUtils.isNotBlank(userIds) ? userIds : actor).append(",");
                }
                createTime = task.getCreateTime();
            }
        }
        if(builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("actors", builder.toString());
        data.put("createTime", createTime);
        return data;
    }
	
	/** 查询用户角色 */
	@SuppressWarnings("rawtypes")
	private String getOperatorNamesByRoleName(String roleName) {
		String names = "";
		
		StringBuilder sql = new StringBuilder();
		sql.append("select t3.operatorname ");
		sql.append("  from AC_OPERATOR t3, AC_OPERATORROLE t2, AC_ROLE t1");
		sql.append(" where t2.operatorid = t3.operatorid");
		sql.append("   and t3.status = ?");
		sql.append("   and t1.roleid = t2.roleid");
		sql.append("   and t1.rolename = ?");
		
		List operatorNames = approvalDao.createSQLQuery(sql.toString(), OPERATOR_STATUS, roleName).list();
		if (!CollectionUtils.isEmpty(operatorNames)) {
			for (Object obj : operatorNames) {
				names += "," + obj.toString();
			}
			
			names = names.substring(1);
		}
		
		return names;
	}
}
